/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.security.iplocator;

import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.base.Charsets;
import com.google.common.collect.Maps;
import org.vacoor.nothing.common.json.Jacksons;
import org.vacoor.nothing.common.util.HttpUtils;
import org.vacoor.nothing.common.util.IOUtils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

/**
 * @author vacoor
 */
public class TaobaoIPLocator implements IPLocator {
    static final String API = "http://ip.taobao.com/service/getIpInfo.php?ip=#IP#";
    static Map<String, JsonNode> cache = Maps.newLinkedHashMap();

    @Override
    public String locate(String ip) {
        try {
            String url = API.replace("#IP#", ip);
            InputStream is = HttpUtils.get(url, null, 1000);
            String s = IOUtils.readText(is, Charsets.UTF_8, true);
            JsonNode root = Jacksons.deserialize(s, JsonNode.class);
            JsonNode data = root.get("data");

            return data.get("country").asText() + /*data.get("area").asText() + */ data.get("region").asText() + data.get("city").asText();
        } catch (IOException e) {
            return null;
        }
    }
}